package com.hmdp.utils;

import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import com.hmdp.mapper.ShopMapper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

@Component
public class BloomFilterInitializer {
    private final StringRedisTemplate stringRedisTemplate;
    private final ShopMapper shopMapper;
    private final BloomFilter<Long> shopIdBloomFilter;

    // 构造函数注入依赖
    public BloomFilterInitializer(StringRedisTemplate stringRedisTemplate, ShopMapper shopMapper) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.shopMapper = shopMapper;
        // 初始化布隆过滤器：预计存储10万商品ID，误判率0.01%
        this.shopIdBloomFilter = BloomFilter.create(
                Funnels.longFunnel(), // 针对Long类型的哈希函数
                100000, // 预期元素数量
                0.0001 // 误判率
        );
    }

    @PostConstruct
    public void init() {
        // 获取所有店铺ID
        List<Long> shopIDs = shopMapper.findAllId();
        shopIDs.forEach(id -> {
            // 添加到布隆过滤器
            shopIdBloomFilter.put(id);
        });
    }

    public boolean mightContain(Long shopId) {
        // 检查店铺ID是否存在于布隆过滤器中
        return shopIdBloomFilter.mightContain(shopId);
    }
}